package com.mazaiting.redeye.module.msg.single

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import cn.jpush.im.android.api.JMessageClient
import cn.jpush.im.android.api.event.MessageEvent
import cn.jpush.im.android.api.event.OfflineMessageEvent
import cn.jpush.im.android.api.model.Conversation
import cn.jpush.im.android.api.model.Message
import cn.jpush.im.api.BasicCallback
import com.chad.library.adapter.base.BaseQuickAdapter
import com.mazaiting.easy.app.IApplicationComponent
import com.mazaiting.easy.base.activity.BaseRefreshToolbarActivity
import com.mazaiting.emotion.fragment.EmotionFragment
import com.mazaiting.emotion.util.GlobalOnItemClickManagerUtil
import com.mazaiting.log.L
import com.mazaiting.redeye.R
import com.mazaiting.redeye.base.ApplicationComponentImpl
import com.mazaiting.redeye.event.UpdateEvent
import com.mazaiting.redeye.utils.ErrorCodeUtil
import kotlinx.android.synthetic.main.activity_single.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.*

/**
 * 单聊页面
 */
class SingleActivity : BaseRefreshToolbarActivity<SinglePresenter>(), SingleContract.View {

    companion object {
        /**
         * 上一个页面传递的数据键
         */
        private const val KEY_USER_NAME = "key_user_name"

        /**
         * 开启单聊页面
         * @param context 上下文
         * @param username 用户名
         */
        fun newInstance(context: Context, username: String) {
            val intent = Intent(context, SingleActivity::class.java)
            intent.putExtra(KEY_USER_NAME, username)
            context.startActivity(intent)
        }
    }

    /**
     * 会话
     */
    private var conversation: Conversation? = null


    override fun getContentLayout(): Int = R.layout.activity_single

    override fun isSlideLock(): Boolean = true

    override fun inject(applicationComponent: IApplicationComponent?) {
        DaggerSingleComponent
            .builder()
            .applicationComponentImpl(applicationComponent as ApplicationComponentImpl)
            .build()
            .inject(this)
    }

    override fun bindView(view: View?, savedInstanceState: Bundle?) {
        // 绑定 EventBus
        EventBus.getDefault().register(this)
        super.bindView(view, savedInstanceState)
        // 禁用刷新
        swipeLayout.isEnabled = false
        // 设置加载条目无动画
        adapter.openLoadAnimation { arrayOf() }
        // 获取按钮
        val btnSend = findViewById<Button>(com.mazaiting.emotion.R.id.bar_btn_send)
        // 获取聊天内容
        val etContent = findViewById<EditText>(com.mazaiting.emotion.R.id.bar_et_content)
        // 绑定输入框
        GlobalOnItemClickManagerUtil.getInstance(this).attachToEditText(etContent)
        // 设置发送事件
        btnSend.setOnClickListener {
            // 设置内容
            val content = etContent.text.toString()
            // 检测内容
            if (TextUtils.isEmpty(content)) return@setOnClickListener
            // 根据当前会话创建待发送的消息
            val message = conversation?.createSendTextMessage(content)
            // 添加消息
            addMessage(message)
            // 设置发送监听
            message?.setOnSendCompleteCallback(object : BasicCallback() {
                override fun gotResult(code: Int, msg: String?) {
//                    L.d("code: $code, msg: $msg")
                    if (code == 0) {
                        //消息发送成功
                        Toast.makeText(this@SingleActivity, "消息发送成功", Toast.LENGTH_SHORT).show()
                    } else {
                        //消息发送失败
                        Toast.makeText(
                            this@SingleActivity,
                            "消息发送失败: ${ErrorCodeUtil.getMessage(code)}",
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                }
            })
            // 清空消息
            etContent.setText("")
            // 发送消息
            JMessageClient.sendMessage(message)
        }
        // 解决 EditText 遮挡 RecyclerView 问题
        recyclerView.addOnLayoutChangeListener { _, _, _, _, bottom, _, _, _, oldBottom ->
//            L.d("bottom: $bottom, oldBottom: $oldBottom")
            // 判断新的底部是否小于就的底部，如果是，则为键盘弹出
            if (bottom < oldBottom) {
                recyclerView.post {
                    // 判断数据是否大于 0
                    if (adapter.itemCount > 0) {
                        scrollToBottom()
                    }
                }
            }
        }
    }

    override fun initData() {
        // 获取用户名
        val username = intent.getStringExtra(KEY_USER_NAME)
        // 设置 Toolbar
        title = username
        // 创建会话
        conversation = Conversation.createSingleConversation(username)
        // 重置未读消息数
        conversation?.resetUnreadCount()
        // 获取全部消息列表
        val allMessage = conversation?.allMessage
        // 创建可操作的列表
        val mutableList = arrayListOf<SingleEntity>()
        // 遍历
        allMessage?.forEach {
            mutableList.add(SingleEntity(it))
        }
        // 添加数据
        adapter.setNewData(mutableList)
        // 滚动到底部
        scrollToBottom()
        // 已读
        EventBus.getDefault().post(UpdateEvent())

        initEmotionFragment()
    }

    /**
     * 表情碎片
     */
    private var mFragment: EmotionFragment? = null

    /**
     * 初始化表情碎片
     */
    private fun initEmotionFragment() {
        // 初始化碎片
        mFragment = EmotionFragment(
            swipe_layout,
            findViewById(R.id.bar_et_content),
            findViewById(R.id.bar_btn_emotion)
        )
        supportFragmentManager
            .beginTransaction()
            .replace(R.id.fl_emotion, mFragment!!)
            .addToBackStack(null)
            .commit()
    }

    override fun onBackPressed() {
        // 判断是否拦截返回键操作
        if (!mFragment!!.isInterceptBackPress()) {
            super.onBackPressed()
        }
    }

    /**
     * 在线消息
     * @param event 事件
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: MessageEvent) {
//        L.d("有消息到来: $event")
        addMessage(event.message)
    }

    /**
     * 离线消息
     * @param event 离线事件
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onOfflineMessageEvent(event: OfflineMessageEvent) {
        // 离线消息列表
        val offlineMessageList = event.offlineMessageList
        L.d("offlineMessageList: $offlineMessageList")
    }

    /**
     * 添加消息
     * @param message 消息
     */
    private fun addMessage(message: Message?) {
        if (null != message) {
            // 添加消息
            adapter.addData(SingleEntity(message))
            // 滚动到底部
            scrollToBottom()
        }
    }

    /**
     * 滚动到底部
     */
    private fun scrollToBottom() {
        // 有动画
        // recyclerView.smoothScrollToPosition(adapter.itemCount)
        // 无动画
        recyclerView.scrollToPosition(adapter.itemCount - 1)
    }

    override fun setAdapter(): BaseQuickAdapter<*, *> = SingleAdapter(ArrayList())

    override fun onDestroy() {
        // 解绑
        EventBus.getDefault().unregister(this)
        super.onDestroy()
    }

}
